package com.mouliu.base.syn10;

/**
 * ThreadLocal使用
 * @author liu.mou
 */
public class ConnThreadLocal {
    public static ThreadLocal<String>th =
            new ThreadLocal<>();

    public void setTh(String val){
        th.set(val);
    }
    public void getTh(){
        System.out.println(Thread.currentThread().getName() + ":" + this.th.get());
    }

    public static void main(String[] args){
        //线程局部变量 只有在当前线程中可见
        final  ConnThreadLocal ct = new ConnThreadLocal();

        Thread t1 =
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ct.setTh("张三");
                        ct.getTh();
                    }
                },"t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    ct.getTh();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2");

        t1.start();
        t2.start();
    }

}
